<template>
  <CloudDialog
    v-model:visible="visible"
    :title="title"
    :width="480"
    :mask-closable="false"
    :before-open="handleOpen"
    :before-ok="handleSubmit"
    :before-close="handleClose">
    <a-form ref="formRef" layout="vertical" :rules="rules" :model="formState">
      <a-form-item label="名称" field="name" hide-asterisk>
        <a-input
          v-model="formState.name"
          :max-length="20"
          show-word-limit
          placeholder="请输入名称"></a-input>
      </a-form-item>
      <a-form-item v-if="record?.id" label="CNAME" field="cname" hide-asterisk>
        <!-- <a-input v-model="formState.cname" placeholder="请输入">
          <template #prepend> region- </template>
          <template #suffix>
            <span class="text-primary cursor-pointer" @click="handleName">
              随机生成
            </span>
          </template>
        </a-input> -->
        <section class="w-full flex items-center cloud-diverse-select">
          <a-input
            v-model="formState.cname"
            placeholder="请输入"
            class="h-32px"
            :max-length="20">
            <template #prepend> region - </template>
            <template #suffix>
              <i-icons-refresh
                class="cursor-pointer hover:text-1"
                @click="handleName" />
            </template>
          </a-input>
          <a-select
            v-model="formState.resolve_domain_id"
            :options="domainOptions"
            placeholder="请选择域名"
            style="
              border-top: 1px solid #dfe2e5;
              border-right: 1px solid #dfe2e5;
              border-bottom: 1px solid #dfe2e5;
              background: #f7f8fa;
            ">
            <template #prefix>.</template>
          </a-select>
        </section>
      </a-form-item>
      <a-form-item
        v-if="!record?.id"
        label="域名"
        field="resolve_domain_id"
        hide-asterisk>
        <a-select
          v-model="formState.resolve_domain_id"
          :options="domainOptions"
          placeholder="请选择域名"></a-select>
      </a-form-item>
    </a-form>
  </CloudDialog>
</template>
<script lang="ts" setup>
import type { AreaItem } from '@/apis/model/resolve'
import {
  addApiResolveRegionApi,
  updateApiResolveRegionApi
} from '@/apis/modules/resolve/area'
import { getApiResolveDomainsApi } from '@/apis/modules/resolve/domain'
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import { omit } from 'lodash-es'
interface IProp {
  record?: AreaItem
}
const visible = defineModel<boolean>('visible', { required: true })
const props = withDefaults(defineProps<IProp>(), {})
const emit = defineEmits(['reload'])

const formRef = ref<FormInstance>()
const formState = reactive({
  name: '',
  cname: '',
  resolve_domain_id: ''
})

const rules: Record<string, FieldRule[] | FieldRule> = {
  name: [{ required: true, message: '请输入名称' }],
  resolve_domain_id: [{ required: true, message: '请选择域名' }],
  cname: cnameRules
}
const domainOptions = ref<LabelValue[]>([])
const title = computed(() => (props.record?.id ? '编辑区域' : '添加区域'))
const handleOpen = async () => {
  try {
    const res = await getApiResolveDomainsApi({ limit: 0 })
    const list = res.list ?? []

    domainOptions.value = list
      .map((item) => ({ label: item.name!, value: item.id! }))
      .filter(Boolean)
  } catch (error) {
    console.error(error)
  }
  if (props.record) {
    formState.name = props.record.name!
    formState.cname = props.record.cname?.replace('region-', '') ?? ''
    formState.resolve_domain_id = props.record.resolve_domain_id!
  }
}
const handleName = () => {
  formState.cname = randomCname()
}
const createArea = async () => {
  const data = { ...omit(formState, ['cname']) }
  await addApiResolveRegionApi(data).then(() => {
    ToastUtils.success('操作成功')
    visible.value = false
    emit('reload')
  })
}
const updateArea = async () => {
  const data = {
    ...formState,
    id: props.record!.id!,
    cname: `region-${formState.cname}`
  }
  await updateApiResolveRegionApi(data).then(() => {
    ToastUtils.success('操作成功')
    visible.value = false
    emit('reload')
  })
}
const handleSubmit = async () => {
  const error = await formRef.value?.validate()

  if (error) return false
  return props.record?.id ? updateArea() : createArea()
}

const handleClose = () => {
  formRef.value?.resetFields()
}
</script>

<style lang="less" scoped>
.arco-input-group {
  .cloud-diverse-select {
    border: 1px solid #d9d9d9;
    border-radius: 0px 4px 4px 0px;
    border-top: 1px solid var(---color-border-4, #dfe2e5);
    border-right: 1px solid var(---color-border-4, #dfe2e5);
    border-bottom: 1px solid var(---color-border-4, #dfe2e5);
    background: var(---color-fill-1, #f7f8fa);
  }
}
.cloud-diverse-select {
  :deep(.arco-input-wrapper) {
    //border-left: none !important;
    border-radius: 0 !important;
  }
  :deep(.arco-select-view) {
    padding-left: 4px;
    border-left: none;
  }
}
</style>
